package lm.concurrency.day7;

import lombok.extern.slf4j.Slf4j;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

import static lm.concurrency.util.Sleeper.sleep;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 10:52 2024/11/19
 */
@Slf4j
public class TimerTest {
    public static void main(String[] args) {
        //method1();
        //method2();
        method3();
    }

    //定时任务 异常不答应该怎么处理
    private static void method4() {
//        ScheduledExecutorService scheduledpool = Executors.newScheduledThreadPool(2);
//        log.debug("task start");
//        scheduledpool.schedule(() -> {
//            log.debug("延时启动 任务1");
//            try {
//                int i = 1 / 0;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }, 2, TimeUnit.SECONDS);
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        log.debug("task start");
        Future<Boolean> future = threadPool.submit(() -> {
            log.debug("延时启动 任务1");
            int i = 1 / 0;
            return true;
        });
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    //定时任务循环执行
    private static void method3() {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
        log.debug("task start");
//        pool.scheduleAtFixedRate(() -> {
//            log.debug("定时启动 任务2");
//            sleep(2);
//        }, 2,1, TimeUnit.SECONDS);

        pool.scheduleWithFixedDelay(() -> {
            log.debug("定时启动 任务3");
            sleep(2);
        }, 2, 1, TimeUnit.SECONDS);
    }

    //单个任务定期启动执行
    private static void method2() {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
        log.debug("task start");
        pool.schedule(() -> {
            log.debug("延时启动 任务1");
        }, 2, TimeUnit.SECONDS);
    }

    //timer本身的问题
    private static void method1() {
        Timer timer = new Timer();
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 1");
                sleep(2);
            }
        };
        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 2");
            }
        };
        // 使用 timer 添加两个任务，希望它们都在 1s 后执行
        // 但由于 timer 内只有一个线程来顺序执行队列中的任务，因此『任务1』的延时，影响了『任务2』的执行
        log.debug("task start");
        timer.schedule(task1, 1000);
        timer.schedule(task2, 1000);
    }
}
